package com.eva.config.exception;

import com.alibaba.fastjson.JSON;
import com.eva.core.exception.BusinessException;
import com.eva.core.model.ApiResponse;
import com.eva.core.constants.ResponseStatus;
import com.eva.core.utils.Utils;
import com.eva.dao.system.model.SystemInterfaceConfig;
import com.eva.service.system.SystemInterfaceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理
 * @author Eva.Caesar Liu
 * @date 2022/02/19 18:03
 */
@Slf4j
@Component
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @Autowired
    private SystemInterfaceConfigService systemInterfaceConfigService;

    /**
     * 业务异常处理
     */
    @ExceptionHandler(BusinessException.class)
    public Object handleBusinessException (BusinessException e, ServletRequest servletRequest) {
        log.error(e.getMessage(), e);
        return this.encryptApiResponse(ApiResponse.failed(e.getCode(), e.getMessage()), servletRequest);
    }

    /**
     * 无权限异常处理
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object handleUnauthorizedException (UnauthorizedException e, ServletRequest servletRequest) {
        log.error(e.getMessage(), e);
        return this.encryptApiResponse(ApiResponse.failed("没有操作权限"), servletRequest);
    }

    /**
     * 参数验证未通过异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException (MethodArgumentNotValidException e, ServletRequest servletRequest) {
        log.error(e.getMessage(), e);
        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        for(FieldError fieldError : bindingResult.getFieldErrors()){
            errors.add(fieldError.getDefaultMessage());
        }
        return this.encryptApiResponse(ApiResponse.failed(ResponseStatus.BAD_REQUEST.getCode(), StringUtils.join(errors)), servletRequest);
    }

    /**
     * 参数验证未通过异常处理
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Object handleMissingServletRequestParameterException (MissingServletRequestParameterException e, ServletRequest servletRequest) {
        log.error(e.getMessage(), e);
        return this.encryptApiResponse(ApiResponse.failed(ResponseStatus.BAD_REQUEST.getCode(), e.getMessage()), servletRequest);
    }

    /**
     * 其它异常处理
     */
    @ExceptionHandler(Exception.class)
    public Object handleException (Exception e, ServletRequest servletRequest) {
        log.error(e.getMessage(), e);
        return this.encryptApiResponse(ApiResponse.failed(ResponseStatus.SERVER_ERROR, e), servletRequest);
    }

    /**
     * 加密ApiResponse
     * @param apiResponse
     * @return
     */
    private Object encryptApiResponse(ApiResponse apiResponse, ServletRequest servletRequest) {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        // 不需要加密
        if (Utils.Secure.disallowEncrypt(httpServletRequest)) {
            return apiResponse;
        }
        // URI不匹配
        String uri = httpServletRequest.getRequestURI();
        uri = uri.replace(httpServletRequest.getContextPath(), "");
        SystemInterfaceConfig interfaceConfig = systemInterfaceConfigService.match(uri);
        if (interfaceConfig == null || !interfaceConfig.getEnableEncrypt()) {
            return apiResponse;
        }
        // 加密
        String response = JSON.toJSONString(apiResponse);
        try {
            return Utils.Secure.encryptResponse(response);
        } catch (SecurityException e) {
            log.error("EVA: encrypt response throw an exception", e);
        }
        return null;
    }
}
